function hide_compound_details(){
        $("#compound_form").hide();
        myLayout.close('east');
	myLayout.close('west');
}

function process_search(){
	var isel = $("#search_input").val();
	if (isel == undefined || isel == "")
        	return;
        search_library_compound();
}

function delete_precursor_compound(precursor_id, reagent){
	$.ajax({
        	type: "POST",
                url:  "/cgi-bin/metabobase/archive_metabobase.cgi",
                data: { 'compound_id': $("#compound_id").val(), 'reagent':reagent, 'precursor_compound':precursor_id, 'datatype':'compound_precursor'},
                success: function(json)
                {
                	$("#compound_form_msg").html("Precursor compound association deleted for product " + $("#compound_id").val());
			refresh_precursor_list("delete", compound_dictionary[precursor_id], reagent_dictionary[reagent]);			
                },
                error:function(xhr,err)
                {
                	alert("Failed deleting precursor compound\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                }
        });
}

function process_compound_precursor(){
	/*var cpsel = $("#compound_precursor").val();
        if (cpsel == undefined || cpsel == "")
                return;
	cpsel = $("ul.typeahead.dropdown-menu").find('li.active').data('value');
	add_precursor(null);
	$("#compound_precursor").val(cpsel);
	//show_precursor_details(false);*/
	$("#derivation_groups").css("display","inline");
}

function search_library_compound(){
        $("#cl_msg").html("searching ... <img src='images/demo_wait.gif' />");
        $("#synonym_changed").val("");
	var search_input = $("#search_input").val();
	if (compoundTable != undefined)
        	compoundTable.fnClearTable();
	$("#compound_library_dialog").html("<img src='images/demo_wait.gif' />");
                        $.ajax({
                                type: "POST",
                                url:  "/cgi-bin/metabobase/get_librarycompounds.cgi",
                                data: {
                                        'search_input': search_input, 'limit': mconfig['compound_search_limit']   
                                },
                                success: function(json)
                                {
                                        $("#compound_library_dialog").hide();
                                        if ($.parseJSON(json) == null){
                                                 new Messi('Error on get_library_compounds.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
					var jo  = $.parseJSON(json);
					$("#cl_msg").html("Found " + jo.aaData.length + " results for " + search_input);
                                        compoundTable = $('#compound_metabo_tbl').dataTable( {
                                                "bProcessing": true,
                                                "iDisplayLength": mconfig['compounds_page_limit'],
                                                "bDestroy": true,
                                                "oLanguage": {
                                                        "sSearch": "Filter:"
                                                },
                                               "aaData": jo.aaData,
						"aaSorting": [[ 2, "desc" ]],
						"aoColumns": [
                                                        { "bVisible": false },
                                                       null,
							{ "bVisible": false },
                                                        null,
                                                        null,
                                                        null,
							null, 
							null
                                                ],
                                                fnDrawCallback: function() {
                                                        update_compound_details();
                                                }
                                        });
					if (jo.aaData.length == 1){
						show_compound_form(jo.aaData[0]);
					}
                                },
                                error:function(xhr,err)
                                {
                                        alert("Failed\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                                }
                        });
} 

function load_compound(json){
	var jo  = $.parseJSON(json);
        compoundTable = $('#compound_metabo_tbl').dataTable( {
        			"bProcessing": true,
                                "iDisplayLength": mconfig['compounds_page_limit'],
                                "bDestroy": true,
                                "oLanguage": {
                                	"sSearch": "Filter:"
                                	},
                                        "aoColumns": [
						{ "bVisible": false },
                                                        null,
						{ "bVisible": false },
                                                        null,
                                                        null,
                                                        null,null,null
                                                ],
                                        "aaData": jo.aaData,
                                                "aaSorting": [[ 2, "desc" ]],
                				fnDrawCallback: function() {
                					update_compound_details();
        					}
        });
	//maxWindow();
}
/*
        add oSearch since compound has ~200k+ records
        */
function init_compound_library(event, ui){
	$("#exp_grps_form").hide();	 
        $("#spectrum_form").hide(); 
                $("#compound_form").hide();
	        $("#compound_spectrum_form").hide();
                if (compoundTable != undefined)
                                compoundTable.fnClearTable();

                        $("#compound_library_dialog").html("<img src='images/demo_wait.gif' />");
                        $.ajax({
                                type: "POST",
                                url:  "/cgi-bin/metabobase/get_librarycompounds.cgi",
				data: {'search_input': null, 'limit': mconfig['compound_search_limit']}, 
                                success: function(json)
                                {
					if ($.parseJSON(json) == null){
                                                 new Messi('Error on init get_library_compounds.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
					$("#cl_msg").html("Displaying latest " + mconfig['compound_search_limit'] + " results");
					add_reagents(add_precursor(load_compound(json)));
                                },
                                error:function(xhr,err)
                                {
                                        alert("Failed\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                                }
                        });
}

function add_precursor(callback){
	var newSource = [];
        $.ajax({
        	type: "POST",
                url:  "/cgi-bin/metabobase/get_hmdbname.cgi",
             	data: {'search_input': null},
		success: function(json)
                	{
                        	$("#compound_library_dialog").hide();
                        	if ($.parseJSON(json) == null){
                                                 new Messi('Error on get_hmdbname.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
			        compound_dictionary  = $.parseJSON(json); //jsoc["compound_info"];//$.parseJSON(json);
				for (var jkey in compound_dictionary){
					newSource.push(compound_dictionary[jkey])
				}
				precursorTypeAhead.data('typeahead').source = newSource.sort(); 
                                csearchTypeAhead.data('typeahead').source = newSource.sort();
				if (callback != null)
					callback;
			},
                 error:function(xhr,err)
                       {
                       		alert("Failed loading compound names\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                       }
        });
}

function add_regroup(keyf){
	var pid = "";
        var precursor_name = $("#compound_precursor").val();
        for (var c in compound_dictionary){
                if (compound_dictionary[c] == precursor_name){
                        pid = c;
                        break;
                }
        }
	var prevformula = "";
        $.ajax({
        	type: "POST",
        	url:  "/cgi-bin/metabobase/get_librarycompounds.cgi",
                data: {
                	'search_input': 'precursor_val', 'precursor_id': pid, 'limit': mconfig['compound_search_limit']
                },
                success: function(json)
                {
			if ($.parseJSON(json) == null){
                                                 new Messi('Error on precursor get_library_compounds.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
                	pre_lcarr  = $.parseJSON(json).aaData[0];
			prevformula = pre_lcarr[2];
			if (prevformula == null || prevformula == ""){
				new Messi('Precursor formula is not set, select a different precursor or check with Daniel', {title: 'Warning'});
				return;
			}
			var groups = "";
			for (var rkey in reagent_group_dictionary){
				var ecounter = $("#" +rkey + "_dg").val();
				if (isNaN(ecounter) || ecounter == "" || ecounter == "0"){
					continue;
				}
				ecounter = parseInt(ecounter);
				for (var i = 0; i < ecounter; i++){
					groups = groups + reagent_group_dictionary[rkey];
				}
			}
			$("#sum_formula").val(prevformula + groups);
			updateFormula();
		},
		error: function(){new Messi('Error retrieving Precursor info for ' + precursor_name, {title: 'Warning'});}
	});	
}

function add_reagents(callback){
        var newSource = [];
        $.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/get_dereagent.cgi",
                data: {'search_input': null},
                success: function(json)
                        {
				if ($.parseJSON(json) == null){
                                                 new Messi('Error on get_dereagent.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
                                var reagent_js = $.parseJSON(json);
				reagent_dictionary = reagent_js["reagents"];
				reagent_group_dictionary = reagent_js["groups"];
				var grp_html = "";//'<dd style="display:inline">';
				var reagent_names = [];
				for (var jkey in reagent_group_dictionary){
					var fid = jkey + '_dg';
					grp_html = grp_html + '<br>&nbsp;<font size="-1">' + jkey + ':' + reagent_group_dictionary[jkey] + '</font>&nbsp;<input type="number" size="5" style="height:30px;width:50px;" value="0" id="' + fid + '" onchange="javascript:add_regroup(\'' + fid + '\')"/>';
				}
				$("#derivation_groups").html(grp_html);
                                var de = $("#derivation_reagent");
				for (var jkey in reagent_dictionary){
                                        reagent_names.push(reagent_dictionary[jkey]);
                                	de.append($("<option/>").attr("value", jkey).text(reagent_dictionary[jkey]));
				}
				reagents["names"] = reagent_names.sort();
				reagents["nameids"] = reagent_dictionary;
				var spectrum_origin_dictionary = reagent_js["spectrum_origin"];
				for (var jkey in spectrum_origin_dictionary){
					$('#spectrum_origin_id')
         				.append($("<option></option>")
         				.attr("value",jkey)
         				.text(spectrum_origin_dictionary[jkey])); 
                                }
                                if (callback != null)
                                        callback;
                        },
                 error:function(xhr,err)
                       {
                                alert("Failed loading compound names\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                       }
        });
}

function refresh_precursor_list(ops, precursor, reagent){
        var annos = {};
        var addedSpAnno = [];
        if (ops == "insert"){
                compound_precursor_arr.push(precursor);
        }else if (ops == "delete"){
		var delposs = [];		
                for (arr in compound_precursor_arr){
                        if (compound_precursor_arr[arr][0] != precursor || compound_precursor_arr[arr][1] != reagent){
				delposs.push(compound_precursor_arr[arr]);
			}
                }
		compound_precursor_arr = delposs;       		
		pre_lcarr = null; 
	}
	
	compoundPrecursorTable = $('#compound_precursor_tbl').dataTable( {
                                        "bProcessing": true,
                                        "bDestroy": true,
                                        "bPaginate":false,
                                        "bInfo":false,
                                        "bFilter":false,
                                        "aaData":compound_precursor_arr
        });
}

function save_precursor(){
	var pid = "";
        var precursor_name = $("#compound_precursor").val();
        for (var c in compound_dictionary){
                if (compound_dictionary[c] == precursor_name){
                        pid = c;
                        break;
                }
        }
	var cid = $("#compound_id").val();
	var reagent = $("#derivation_reagent").val();
	var showpc = "<a href=javascript:show_precursor_details('" + pid + "')>Details</a>";
	var deletepc = "<a href=javascript:delete_precursor_compound('" + pid + "','" + reagent + "')>Delete</a>"; 
	var precursor_oa = [precursor_name, reagent_dictionary[reagent],showpc, deletepc];
	$.ajax({
        	type: "POST",
                url:  "/cgi-bin/metabobase/update_compound_precursors.cgi",
                data: {
                	'compound_id': cid,'precursor_compound_id': pid,'derivatization_reagent_id': reagent
                },
                success: function(json){
			if ($.parseJSON(json) == null){
                                                 new Messi('Error on update_compound_precursors.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
                	var jo  = $.parseJSON(json);
			$("#compound_form_msg").html("Updated compound " + cid + " precursor " + precursor_name + " associated");
			refresh_precursor_list("insert", precursor_oa);
                },
                error:function(xhr,err){
                        alert("Failed saving new precursor \nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                }
        });    
}

function edit_precursor_details(){
	myLayout.close('west');
	show_compound_form(pre_lcarr);
}

function show_precursor_details(pid){
	/*var pid = "";
	var precursor_name = $("#compound_precursor").val();
        for (var c in compound_dictionary){
                if (compound_dictionary[c] == precursor_name){
                        pid = c;
                        break;
                }
        }*/
	$("#chart_div").html("");
	$("#chart_table_div").html("");
        $("#compound_library_dialog").html("<img src='images/demo_wait.gif' />");
	$.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/get_compound_precursors.cgi",
                data: {'compound_id': pid},
                success: function(json){
                        	if ($.parseJSON(json) == null){
                                                 new Messi('Error on get_compound_precursors.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
			        var jsobj = $.parseJSON(json);
                                var precursor_arr = jsobj["precursorCompoundData"];        
		        $.ajax({
                                type: "POST",
                                url:  "/cgi-bin/metabobase/get_librarycompounds.cgi",
                                data: {
                                        'search_input': 'precursor_val', 'precursor_id': pid, 'limit': mconfig['compound_search_limit']
                                },
                                success: function(json)
                                {
					if ($.parseJSON(json) == null){
                                                 new Messi('Error on precursor get_library_compounds.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
					var precursor_info_str = "";
					for (arr in precursor_arr){
						precursor_info_str = precursor_info_str + precursor_arr[arr][0] + ":" + precursor_arr[arr][1] + "<br>"
					}
					pre_lcarr  = $.parseJSON(json).aaData[0];
					var precursor_val = "";
					if (pre_lcarr[16] != undefined && pre_lcarr[16].length > 0){
                               			precursor_val = compound_dictionary[pre_lcarr[16]];
                        		}
					var pubchem = "";
					if (pre_lcarr[8].length > 1)
                         	       		pubchem = '<a href="http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid=' + pre_lcarr[8] +'" target="_blank">reference</a>';
					var chemspider = "";
					if (pre_lcarr[11].length > 1)
						chemspider = '<a href="http://www.genome.jp/dbget-bin/www_bget?' + pre_lcarr[11] +'" target="_blank">reference</a>';
                        		var kegg = "";
					if (pre_lcarr[18].length > 1)
						kegg = '<a href="http://www.genome.jp/dbget-bin/www_bget?' + pre_lcarr[18]+ '" target="_blank">reference</a>';
				        var structure_html = "";
					var structureid = pre_lcarr[pre_lcarr.length-1];
		                        if (structureid != null && structureid.length > 1 && structureid != "None"){
                	                	structure_html = '<p><a href="http://metabolomics.uni.lux/~dweindl/mddb/struc_svg.php?cid=' + structureid + '" target="_blank"><img border="0" src="http://metabolomics.uni.lux/~dweindl/mddb/struc_svg.php?cid=' + structureid + '" width="50%" height="20"></a></p>';
                        		}
					var precursor_str = '<a href="#" onclick="edit_precursor_details();">Edit</a>&nbsp;' + pid + "<br>Name:" + compound_dictionary[pid] 
					+ structure_html
					+ "<br>Synonyms:<br>" + "<br>Precursor:Reagent<br>" + precursor_info_str  + "<br>" + "<br>Formula:" + pre_lcarr[2] + "<br>" 
					+ "<br>Nominal mass:" + pre_lcarr[3] + "<br>" + "<br>Molecular weight:" + pre_lcarr[4] + "<br>" + "<br>Monoisotopic mass:" + pre_lcarr[5] + "<br>" + "<br>Spectrum id:" + pre_lcarr[6] + "<br>" + "<br>CAS:"+ pre_lcarr[7] + "<br>" + "<br>Pubchem:"+ pubchem + "<br>" + "<br>NIST:"+ pre_lcarr[10]  +"<br>" + "<br>Chemspider:"+ chemspider  +"<br>" + "<br>KEGG:"+ kegg  +"<br>" + "<br>Inchi:"+ pre_lcarr[14]  +"<br>" + "<br>Inchi key:"+ pre_lcarr[15]  +"<br>" + "<br>User comments:"+ pre_lcarr[13]  +"<br>";
       					 $("#precursor_details_view").html(precursor_str);
        				//if (doshow == true){
					myLayout.open('west');
                                        //myLayout.close('center');
					//}
                                },
                                error:function(xhr,err)
                                {
                                        alert("Failed\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                                }
                        });
		}	
	});
}

function load_compound_synonyms(compound_id,callback){
        $.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/get_compound_syn.cgi",
                data: {'compound_id': compound_id},
                success: function(json)
                        {
				if ($.parseJSON(json) == null){
                                                 new Messi('Error on get_compound_synonym.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
				var syns = $.parseJSON(json);
				var synstr = "";
                                for (var syn in syns){
                                        synstr = synstr + syn + "\n";
                                }       
                                $("#compound_synonym").val(synstr);
				callback;
                        },      
                 error:function(xhr,err)
                       {
                                alert("Failed loading compound names\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                       }
        });
}
function update_synflag(){
	$("#synonym_changed").val("changed");
}

function get_precursor_compounds(lcarray, callback){
	$.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/get_compound_precursors.cgi",
                data: {'compound_id': lcarray[0]},
                success: function(json)
                        {
				if ($.parseJSON(json) == null){
                                                 new Messi('Error on get_compound_precursors.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
				var jsobj = $.parseJSON(json);
                        	compound_precursor_arr = jsobj["precursorCompoundData"];
    				compoundPrecursorTable = $('#compound_precursor_tbl').dataTable( {
                        		"bProcessing": true,
                        		"bDestroy": true,
                        		'bPaginate':false,
                        		'bInfo':false,
                        		'bFilter':false,
                        		"aaData": compound_precursor_arr
         			});
                                callback(lcarray);
                        },
                 error:function(xhr,err)
                       {
                                alert("Failed loading compound precursors \nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                       }
        });
}

function populate_compound_form(lcarr){
	if (compoundPrecursorTable != undefined)
		compoundPrecursorTable.fnClearTable();
	var addSpectrum = "<br><a href=javascript:show_spectrum_form(null)><font size='-2'>Add Spectrum</font></a>&nbsp;<a href=javascript:show_spectrum_annotation_form(null)><font size='-2'>Mass spectra</font></a>";
	$("#compound_form_msg").html("Updating compound " + lcarr[0] + addSpectrum);
        get_precursor_compounds(lcarr, function(lcarr){
                $("#compound_id").val(lcarr[0]);
                $("#compound_name").val(lcarr[1]);
			$("#sum_formula").val(lcarr[4]);
                        $("#nominal_mass").val(lcarr[5]);
                        $("#molecular_weight").val(lcarr[6]);
                        $("#monoisotopic_mass").val(lcarr[7]);
                        $("#reference_spectrum_id").val(lcarr[8]);
                        $("#ref_cas_id").val(lcarr[9]);
                        $("#ref_pubchem_id").val(lcarr[10]);
                        $("#ref_hmdb_id").val(lcarr[11]);
			if (lcarr[10].length > 1){
				$("#pubchem_deeplink").html('<a href="http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid=' + lcarr[10] +'" target="_blank">Pubchem</a>');
			}
			if (lcarr[11].length > 1){
                                $("#hmdb_deeplink").html('<a href="http://www.hmdb.ca/metabolites/' + lcarr[11] +'" target="_blank">HMDB</a>');
                        }
                        $("#ref_nist_id").val(lcarr[12]);
                        $("#ref_chemspider_id").val(lcarr[13]);
                        $("#chemspider_deeplink").html('<a href="http://www.genome.jp/dbget-bin/www_bget?' + lcarr[13] +'" target="_blank">Chemspider </a>id');
                        if (lcarr[14] != null && lcarr[14] == 'Y'){
                                document.getElementById("lcchecked").checked = true;
                        }else{
                                document.getElementById("lcchecked").checked = false;
                        }
                        $("#lccomment").val(lcarr[15]);
                        $("#inchi").val(lcarr[16]);    
                        $("#inchi_key").val(lcarr[17]);
			$("#derivation_reagent").val(lcarr[19]);  
                        if (lcarr[18] != undefined && lcarr[18].length > 0){
                                $("#precursor_mode").val("update");
                                $("#compound_precursor").val("");
				//$("#compound_precursor").val(compound_dictionary[lcarr[18]]);
                        	//$("#precursor_details").html("<a href=javascript:show_precursor_details(null)>Details</a>");
				//$("#derivation_reagent").val("na");
			}else{
				$("#precursor_details").html("");
                                $("#precursor_mode").val("insert");
                                $("#compound_precursor").val("");//lcarr[18]);
				//$("#derivation_reagent").val("na");
                        }
                        $("#derivation_reagent").val("na");
                        $("#kegg_deeplink").html('<a href="http://www.genome.jp/dbget-bin/www_bget?' + lcarr[20]+ '" target="_blank">KEGG </a>id');
                        $("#ref_kegg_id").val(lcarr[20]);
			var structureid = lcarr[lcarr.length-1];
			if (structureid != null && structureid.length > 1){
				$("#structure_span").html('<p><a href="http://metabolomics.uni.lux/~dweindl/mddb/struc_svg.php?cid=' + structureid + '" target="_blank"><img border="0" src="http://metabolomics.uni.lux/~dweindl/mddb/struc_svg.php?cid=' + structureid + '" width="50%" height="20"></a></p>');
			}
	});
}

function show_compound_form(lcarr){
	//get synonyms for compound_id if it is not new
	$("#structure_span").html("");
	$("#spectrum_form").hide();
	$("#spectrum_annotation_form").hide();
	hideExperimentGroups();

	var addSpectrum = "<br><a href=javascript:show_spectrum_form(null)><font size='-2'>Add Spectrum</font></a>";
	if (lcarr != null && lcarr == "current"){
		lcarr = current_lcarr;
	}	
	if (lcarr != null){
		current_lcarr = lcarr;
		for (var i = 0; i < lcarr.length; i++){
                        if (lcarr[i] == "None"){
                                lcarr[i] = "";
                        }
                }		
		load_compound_synonyms(lcarr[0], populate_compound_form(lcarr));
	}else{
		$("#compound_form_msg").html("Adding new compound" + addSpectrum);
		compound_precursor_arr = [];
		$('#compound_precursor_tbl').find("tr:gt(0)").remove();	
		init_new_compound();
	}
	for (var jkey in reagent_group_dictionary){
                $("#" + jkey + "_dg").val("0");
	}
	$("#derivation_groups").css("display","none");
        $("#compound_form").show();
	myLayout.open('east'); 
}

/*
Maybe use as a clear/reset function as well
compound_id,compound_name,sum_formula,nominal_mass,molecular_weight,monoisotopic_mass,reference_spectrum_id,ref_cas_id,ref_pubchem_id,ref_hmdb_id,ref_nist_id,ref_chemspider_id,time_added,time_lastmod,comment,checked
*/
function init_new_compound(){
	$("#compound_id").val("");
	$("#compound_name").val("");
	$("#sum_formula").val("");
	$("#nominal_mass").val("");
	$("#molecular_weight").val(""); 
	$("#monoisotopic_mass").val("");
	$("#reference_spectrum_id").val("");
	$("#ref_cas_id").val("");
	$("#ref_pubchem_id").val("");    	
	$("#ref_hmdb_id").val("");
	$("#ref_nist_id").val("");
	$("#ref_chemspider_id").val("");
	$("#ref_kegg_id").val("");
	document.getElementById("lcchecked").checked = false;
	$("#lccomment").val("");
	$("#inchi").val("");
	$("#inchi_key").val("");
        $("#derivation_reagent").val("na");
	$("#compound_precursor").val("");
	$("#compound_synonym").val("");
	$("#precursor_mode").val("insert");	
	$("#precursor_details").html("");
	$("#structure_span").html("");
	for (var jkey in reagent_group_dictionary){
        	$("#" + jkey + "_dg").val("0");
        }
        $("#derivation_groups").css("display","none");
	 $("#synonym_changed").val("");
	reset_spectrum_form();
}

function delete_library_compound(){
        new Messi('Are you sure you want to delete this compound ' + $("#compound_name").val() + '?', {title: 'Buttons', buttons: [{id: 0, label: 'Yes', val: 'Y'}, {id: 1, label: 'No', val: 'N'}],
                callback: function(val) { if (val == 'Y'){
			$("#compound_library_dialog").html("<img src='images/demo_wait.gif' />");
        		$.ajax({
                	type: "POST",
                	url:  "/cgi-bin/metabobase/archive_metabobase.cgi",
                	data: { 'compound_id': $("#compound_id").val(), 'datatype':'compound'},
                                success: function(json)
                                {
                                        $("#compound_library_dialog").hide();
                                        $("#compound_form_msg").html("Compound deleted for id " + $("#compound_id").val());
                                        hide_compound_details();
					new Messi('Compound deleted, refresh or do new search to update grid list', {title: 'Done', autoclose: 2000});
					//process_search();
                                },
                                error:function(xhr,err)
                                {
                                        alert("Failed post\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                                }
                        });
		}}});
}

/*
Update needs to include compound_id
*/
function post_library_compound(lcobj){
	if (isFormValid() == false){
		return;
	}
        var compound_id = $("#compound_id").val();
        var lcname = $("#compound_name").val();
	var sum_formula = $("#sum_formula").val();
        var nominal_mass = $("#nominal_mass").val();
	var molecular_weight = $("#molecular_weight").val();
	var monoisotopic_mass = $("#monoisotopic_mass").val();
	var reference_spectrum_id = $("#reference_spectrum_id").val();
	var ref_cas_id = $("#ref_cas_id").val();
	var ref_pubchem_id = $("#ref_pubchem_id").val();
	var ref_hmdb_id = $("#ref_hmdb_id").val();
	var ref_nist_id = $("#ref_nist_id").val();
	var ref_chemspider_id = $("#ref_chemspider_id").val();
	var ref_kegg_id = $("#ref_kegg_id").val();
	var lccomments = $("#lccomment").val();
	var inchi = $("#inchi").val();
	var inchi_key = $("#inchi_key").val();
	var precursor = "";
	var precursor_name = $("#compound_precursor").val();
	if (precursor_name != undefined && precursor_name.length > 2){
		for (var c in compound_dictionary){
			if (compound_dictionary[c] == precursor_name){
				precursor = c;
				break;
			}
		}
	}
	var reagent = $("#derivation_reagent").val();
	/*if (reagent == "na"){
		reagent = null;
	}*/
	var precursor_mode = $("#precursor_mode").val();
        var checkedval = 'N';
	if (document.getElementById("lcchecked").checked)
		checkedval = 'Y';
	var compound_synonym = $("#compound_synonym").val();
	var csyn_flag = $("#synonym_changed").val();
	if (compound_synonym == ""){
		csyn_flag = "";
	}
	$("#compound_library_dialog").html("<img src='images/demo_wait.gif' />");
	$.ajax({
                                type: "POST",
                                url:  "/cgi-bin/metabobase/update_librarycompounds.cgi",
                                data: {
                                        'compound_id': compound_id,'compound_name': lcname,'sum_formula': sum_formula, 'nominal_mass':nominal_mass, 'molecular_weight':molecular_weight, 'monoisotopic_mass':monoisotopic_mass, 'reference_spectrum_id':reference_spectrum_id, 'ref_cas_id':ref_cas_id, 'ref_pubchem_id':ref_pubchem_id, 'ref_hmdb_id':ref_hmdb_id, 'ref_nist_id':ref_nist_id, 'ref_chemspider_id':ref_chemspider_id, 'ref_kegg_id':ref_kegg_id, 'lccomment': lccomments, 'lcchecked': checkedval, 'inchi': inchi, 'inchi_key': inchi_key, 'compound_precursor':precursor, 'derivation_reagent':reagent, 'precursor_mode': precursor_mode, 'compound_synonym':compound_synonym, 'csyn_flag':csyn_flag 
                                },
                                success: function(json)
                                {
					if ($.parseJSON(json) == null){
                                                 new Messi('Error on update_librarycompounds.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});
                                        }
                                        $("#compound_library_dialog").hide();
                                        var jo  = $.parseJSON(json);
					var addSpectrum = "<br><a href=javascript:show_spectrum_form(null)><font size='-2'>Add Spectrum</font></a>&nbsp;<a href=javascript:show_spectrum_annotation_form(null)><font size='-2'>Mass spectra</font></a>";
					$("#compound_form_msg").html("Compound '" + jo["_cname"] + "' updated/saved " + addSpectrum);
					//myLayout.close('east');
					new Messi('Compound ' + jo["_cname"] + 'saved/modified', {title: 'Success', autoclose:1500});
					search_library_compound();
                        		myLayout.close('west');
					$("#compound_id").val(jo["_cid"]);
                                },
                                error:function(xhr,err)
                                {
                                        alert("Failed post\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                                }
                        });		        
}

function update_compound_details(){
	$('#compound_metabo_tbl tbody tr').unbind('dblclick').bind('dblclick', function () {
                        var selectedData = compoundTable.fnGetData( this );
                        var iId = selectedData[0];
			show_compound_form(selectedData);
                        return;
       });
}

function updateFormula(formula){
	var formula = $("#sum_formula").val();
	var mwo = calculateMassAndWeight(formula);
	$("#molecular_weight").val(mwo["mw"]);
        $("#monoisotopic_mass").val(mwo["im"]);
        $("#nominal_mass").val(mwo["nm"]);
}

function updateSpectrumFormula(){
	var formula = $("#spa_formula").val();
        var mwo = calculateMassAndWeight(formula);
        $("#spa_peak_mz").val(mwo["nm"]);
}

function updateSpectrumMZ(){
	var formula = $("#spa_formula").val();
        var mwo = calculateMassAndWeight(formula);
        var val = mwo["nm"];
	var mzchanged = $("#spa_peak_mz").val();
	if (val != mzchanged){
		new Messi('Updated m/z value is not matching computed formula nominal mass', {title: 'm/z value warning', autoclose:2000});	
	}

}
function calculateMassAndWeight(formula){
	var massweight = {};
        var ftk = formula.split("");
	var elements = {};
	var element = "";
	var totalElements = 0;
	var index = 0;
	for (var i = 0; i< ftk.length; i++){
		if (!isNumeric(ftk[i]) && isUpperCase(ftk[i])){
			element = ftk[i];
			index = i;
			if (i+1 < ftk.length && !isNumeric(ftk[i+1]) && isLowerCase(ftk[i+1])){
				element = ftk[i] + ftk[i+1];
				index = i+1;
			}
			elements[index] = element;
			totalElements++;			
		}
	}
	var molecularWeight = 0;
	var isoMass = 0;
	var nominalMass = 0;
	var pe = 0;
	var prevIndex = 0;
	var ct = 0;
	for (var e in elements){
		if (ct > 0){
			var ec = parseInt(e) - prevIndex;
			e = parseInt(e);
			var ec = parseInt(formula.substring(prevIndex+1,e));
			if (prevIndex+1 == e || isNaN(ec)){
				ec = 1;
			}
			molecularWeight = molecularWeight + ec*parseFloat(element_atomicweight[pe]);
			isoMass = isoMass + ec*parseFloat(element_monoisomass[pe]);
			nominalMass = nominalMass + ec*Math.round(parseFloat(element_monoisomass[pe]));
		} 
		pe = elements[e];
		ct++;
		if (ct == totalElements){
			var lastI = parseInt(e) + 1;
			var lc = 1;
			if (lastI < ftk.length){
			lc = "";
			while (lastI < ftk.length){
				lc = lc + ftk[lastI];
				lastI++;
			}
			lc = parseInt(lc);
			}
			molecularWeight = molecularWeight + ((lc)*parseFloat(element_atomicweight[pe]));
			isoMass = isoMass + ((lc)*parseFloat(element_monoisomass[pe]));
			nominalMass = nominalMass + ((lc)*Math.round(parseFloat(element_monoisomass[pe])));
		}
		prevIndex = parseInt(e);
	}
	massweight["mw"] = molecularWeight;
	massweight["im"] = isoMass;
	massweight["nm"] = nominalMass;
	return massweight;
	//$("#molecular_weight").val(molecularWeight);
	//$("#monoisotopic_mass").val(isoMass);
	//$("#nominal_mass").val(nominalMass);
}

/*
var element_monoisomass 
var element_atomicweight
*/
function isFormValid(){
	//name can not be blank or less than 4 characters
	if ($("#compound_name").val() == undefined || $("#compound_name").val().length < 3){
		$("#compound_form_msg").html("Compound name is required");
		new Messi('Compound name is required', {title: 'Validation error', autoclose:1500});
		return false;
	}
	if ($("#compound_precursor").val() != undefined && $("#compound_precursor").val().length > 1 && $("#derivation_reagent").val() == "na"){
		$("#compound_form_msg").html("Derivation agent required with selection of compound precursor");
		new Messi('Compound precursor and derivation reagent are required together', {title: 'Validation error', autoclose:1500});	
		return false;
	}

	if (($("#compound_precursor").val() == undefined || $("#compound_precursor").val() == "") && $("#derivation_reagent").val() != "na"){
                $("#compound_form_msg").html("Derivation agent required with selection of compound precursor");
                new Messi('Compound precursor and derivation reagent are required together', {title: 'Validation error', autoclose:1500});
                return false;
        }
	return true;	
}
